import { fileURLToPath, URL } from 'node:url'
import { type ConfigEnv, loadEnv, defineConfig } from 'vite'
import { getPluginsList } from './build/plugins'
import { convertEnv } from './build/utils'

// https://vite.dev/config/
export default defineConfig((configEnv: ConfigEnv) => {
  const viteEnv = convertEnv(loadEnv(configEnv.mode, process.cwd()))
  const { VITE_PUBLIC_PATH, VITE_PORT, VITE_USE_MOCK } = viteEnv
  return {
    base: VITE_PUBLIC_PATH,
    server: {
      port: VITE_PORT,
      host: '0.0.0.0',
      // 预热文件以提前转换和缓存结果，降低启动期间的初始页面加载时长并防止转换瀑布
      warmup: {
        clientFiles: ['./index.html', './src/{views,components}/*'],
      },
    },
    preview: {
      port: VITE_PORT,
      host: '0.0.0.0',
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    plugins: getPluginsList(VITE_USE_MOCK),
    build: {
      // https://cn.vitejs.dev/guide/build.html#browser-compatibility
      target: 'es2015',
      sourcemap: false,
      // 消除打包大小超过500kb警告
      chunkSizeWarningLimit: 4000,
      rollupOptions: {
        input: {
          index: fileURLToPath(new URL('./index.html', import.meta.url)),
        },
        // 静态资源分类打包
        output: {
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
        },
      },
    },
  }
})
